package com.lab303.powerproject.controller;

import com.lab303.powerproject.entity.Device;
import com.lab303.powerproject.entity.EnergyType;
import com.lab303.powerproject.entity.GraphInfo;
import com.lab303.powerproject.entity.Relationship;
import com.lab303.powerproject.pojo.CustomAtlasViewDevice;
import com.lab303.powerproject.pojo.CustomDevice;
import com.lab303.powerproject.pojo.CustomRelationshipObject;
import com.lab303.powerproject.service.DeviceService;
import com.lab303.powerproject.service.EnergyTypeService;
import com.lab303.powerproject.service.GraphInfoService;
import com.lab303.powerproject.service.RelationshipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("relationship")
public class RelationshipController {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RelationshipService relationshipService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private EnergyTypeService energyTypeService;

    /**
     * 获取出指定设备id的其他所有设备
     * @param deviceId
     * @return
     */
    @GetMapping("/getnodes")
    @ResponseBody
    public List getAllNode(Integer deviceId){
        List<CustomDevice> devices = deviceService.findDevices();
        if (deviceId!=null) {
            int i = 0;
            for (; i < devices.size(); i++) {
                if (devices.get(i).getDeviceId() == deviceId) break;
            }
            devices.remove(i);
        }
        return devices;
    }

    /**
     * 根据边id删除边
     * @param relId
     * @return
     */
    @GetMapping("/delete/{relId}")
    @ResponseBody
    public String deleteRelationship(@PathVariable("relId")Integer relId){
        relationshipService.deleteRelationshipById(relId);
        return "success";
    }

    /**
     * 将尸体设备类转化为自定义类
     * @param deviceList
     * @return
     */
    private List deviceToCustomAtlasViewDevice(List<Device> deviceList){
        List<CustomAtlasViewDevice> res = new ArrayList<>();
        for (Device device:deviceList){
            CustomAtlasViewDevice customAtlasViewDevice = new CustomAtlasViewDevice();
            customAtlasViewDevice.setDeviceId(device.getDeviceId());
            customAtlasViewDevice.setCap(device.getCap());
            customAtlasViewDevice.setConversionRate(device.getConversionRate());
            customAtlasViewDevice.setCreate_time(device.getCreate_time());
            customAtlasViewDevice.setDeviceName(device.getDeviceName());
            customAtlasViewDevice.setHighlightPicPath(device.getHighlightPicPath());
            customAtlasViewDevice.setPicPath(device.getPicPath());
            customAtlasViewDevice.setIsPredicted(device.getIsPredicted());
            customAtlasViewDevice.setPower(device.getPower());
            customAtlasViewDevice.setWorkTime(device.getWorkTime());
            customAtlasViewDevice.setCoordinate(new float[]{device.getxCoordinates(),device.getyCoordinates()});
            List customRelationship = relationshipService.findCustomRelationship(device.getDeviceId());
            customAtlasViewDevice.setRelationship(customRelationship);
            res.add(customAtlasViewDevice);
        }
        return res;
    }

    /**
     * 根据月份判断显示图谱
     * @return
     * @throws ParseException
     */
    @GetMapping("/getViewAtlas")
    @ResponseBody
    public Map getViewAtlas() throws ParseException {   //view.html图谱，根据月份判断的
        Map map = new HashMap();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        int graphId = graphInfoList.get(0).getGraphId();
        for (GraphInfo g:graphInfoList){
            Date startTime = format.parse(g.getGraphStartTime());
            Date endTime = format.parse(g.getGraphEndTime());
            if (date.after(startTime)&&date.before(endTime)){
                graphId = g.getGraphId();
                break;
            }
        }
        List<Device> atlasDevice = deviceService.findDevicesByGraphId(graphId);
        List res = deviceToCustomAtlasViewDevice(atlasDevice);
        List<Map> edge = relationshipService.getEdgeByGraphId(graphId);
        map.put("node",res);
        map.put("edge",edge);
        return map;
    }

    /**
     * 根据图谱id获取图谱的所有信息，包括点和边
     * @param graphId
     * @return
     */
    @GetMapping("/getGraphDragChart/{graphId}")
    @ResponseBody
    public Map getGraphDragChart(@PathVariable("graphId")Integer graphId){
        Map mapList = new HashMap();
        List<Device> atlasDevice = deviceService.findDevicesByGraphIdAnIsInGraph(graphId,1);
        List res = deviceToCustomAtlasViewDevice(atlasDevice);
        List<Map> edge = relationshipService.getEdgeByGraphId(graphId);
        mapList.put("node",res);
        mapList.put("edge",edge);
        mapList.put("graphId",graphId);
        return mapList;
    }


    /**
     * 跳转可拖拽图谱的界面
     * @param model
     * @return
     */
    @GetMapping("/viewDragPage")
    public String viewDragPage(Model model){
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        if (graphInfoList.size()>0){
            model.addAttribute("graphId",graphInfoList.get(0).getGraphId());
        }
        model.addAttribute("graphList",graphInfoList);
        return "dragChart";
    }

    /**
     * 跳转指定的可拖拽图谱界面
     * @param graphId
     * @param model
     * @return
     */
    @GetMapping("/viewDragPage/{graphId}")
    public String viewDragPage(@PathVariable("graphId")Integer graphId,Model model){
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("graphList",graphInfoList);
        model.addAttribute("graphId",graphId);
        return "dragChart";
    }

    /**
     * 跳转所有边列表界面
     * @param model
     * @return
     */
    @GetMapping("/viewRelationship")
    public String viewRelationship(Model model){
        List relationshipList = relationshipService.findCustomRelationshipList();
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("relationshipList",relationshipList);
        model.addAttribute("graphInfoList",graphInfoList);
        return "edge";
    }

    /**
     * 跳转添加边页面
     * @param graphId
     * @param model
     * @return
     */
    @GetMapping("/add/{graphId}")
    public String addPage(@PathVariable("graphId") Integer graphId,Model model){
        GraphInfo graphInfoById = graphInfoService.findGraphInfoById(graphId);
        model.addAttribute("graphInfo",graphInfoById);
        return "edgeAdd";
    }

    /**
     * 跳转到修改边关系界面
     * @param rid
     * @param model
     * @return
     */
    @GetMapping("/get/{rid}")
    public String editPage(@PathVariable("rid") Integer rid,Model model){
        Relationship relationship = relationshipService.findRelationshipById(rid);
        model.addAttribute("relationship",relationship);
        GraphInfo graphInfoById = graphInfoService.findGraphInfoById(relationship.getGraphId());
        List devices = deviceService.getDevicesByGraphId(graphInfoById.getGraphId());
        List<EnergyType> energyType = energyTypeService.getAllEnergyType();
        model.addAttribute("deviceList",devices);
        model.addAttribute("energyTypeList",energyType);
        model.addAttribute("graphName",graphInfoById.getGraphName());
        return "edgeEdit";
    }

    /**
     * 处理添加边请求
     * @param graphId
     * @param request
     * @return
     */
    @PostMapping("/addEdge")
    @ResponseBody
    public Map addRelationship(Integer graphId,HttpServletRequest request){
        Map res = new HashMap();
        List<Relationship> addList = new ArrayList<>();
        List<String> duplicateList = new ArrayList<>();
        String[] lossRates = request.getParameterValues("lossRate");
        String[] deviceFroms = request.getParameterValues("deviceFrom");
        String[] deviceTos = request.getParameterValues("deviceTo");
        String[] energyTypeIds = request.getParameterValues("energyTypeId");
        String[] isShards = request.getParameterValues("isShard");
        for (int i = 0;i<lossRates.length;i++){
            Relationship relationship = new Relationship(Integer.parseInt(deviceFroms[i]),Integer.parseInt(deviceTos[i]),Float.parseFloat(lossRates[i]),Integer.parseInt(energyTypeIds[i]),graphId,Integer.parseInt(isShards[i]));
            if (!relationshipService.checkDuplicateRelationship(relationship)){
                addList.add(relationship);
            }else {
                String deviceFromName = deviceService.findCustomDeviceById(relationship.getDeviceFrom()).getDeviceName();
                String deviceToName = deviceService.findCustomDeviceById(relationship.getDeviceTo()).getDeviceName();
                duplicateList.add(deviceFromName+"到"+deviceToName+"的策略已存在");
            }
        }
        if (addList.size()>0){
            relationshipService.saveRelationshipList(addList);
            res.put("message","save"+addList.size()+"relationship");
        }
        if (duplicateList.size()>0){
            res.put("duplicateList",duplicateList);
            res.put("status","dissatisfied");
        }else {
            res.put("status","satisfied");
        }
        return res;
    }

    /**
     * 获取指定图谱的所有边
     * @param graphId
     * @param model
     * @return
     */
    @GetMapping("/viewRelationship/{graphId}")
    public String viewRelationshipById(@PathVariable("graphId")Integer graphId,Model model){
        List<CustomRelationshipObject> list = relationshipService.findCustomRelationshipListByGraphId(graphId);
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("relationshipList",list);
        model.addAttribute("graphInfoList",graphInfoList);
        return "edge";
    }


    /**
     * 获取对应图谱的设备列表
     * @param graphId
     * @return
     */
    @GetMapping("/graphAndEnergyTypeList/{graphId}")
    @ResponseBody
    public Map graphAndEnergyTypeList(@PathVariable("graphId")Integer graphId){
        List<EnergyType> allEnergyType = energyTypeService.getAllEnergyType();
        List devices = deviceService.findDevicesByGraphIdAnIsInGraph(graphId,1);
        Map res = new HashMap();
        res.put("energyTypeList",allEnergyType);
        res.put("deviceList",devices);
        return res;
    }

    /**
     * 处理修改边请求
     * @param relationship
     * @return
     */
    @PostMapping("/updateRelationship")
    @ResponseBody
    public Map updateRelationship(Relationship relationship){
        Map map = new HashMap();
        Relationship updateRelationship = null;
        Relationship b = relationshipService.findRelationshipByFromAndToAndGraphId(relationship);
        if (b==null||b.getId()==relationship.getId()) {
            updateRelationship = relationshipService.updateRelationship(relationship);
        }else {
            String deviceFromName = deviceService.findCustomDeviceById(relationship.getDeviceFrom()).getDeviceName();
            String deviceToName = deviceService.findCustomDeviceById(relationship.getDeviceTo()).getDeviceName();
            String str = deviceFromName+"到"+deviceToName+"的策略已存在";
            map.put("duplicate_message",str);
        }
        if (updateRelationship!=null){
            map.put("message","success");
        }else {
            map.put("message","fail");
        }
        return map;
    }


}
